package com.lottery.material.controller.admin.system;

import com.lottery.material.common.JsonResult;
import com.lottery.material.controller.base.BaseController;
import com.lottery.material.entity.admin.Role;
import com.lottery.material.entity.admin.User;
import com.lottery.material.service.admin.system.RoleService;
import com.lottery.material.service.admin.system.UserService;
import com.lottery.material.utils.EmptyUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description：用户Controller
 * Created by 朱正磊 on 2019-03-26 16:55
 */
@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController {

    private final String PATH = "admin/user/";

    private final UserService userService;

    private final RoleService roleService;

    @Autowired
    public UserController(UserService userService, RoleService roleService) {
        this.userService = userService;
        this.roleService = roleService;
    }

    /**
     * description：请求访问用户主页
     * user 朱正磊
     * time 2019-03-26 17:14
     * @return 返回模型视图
     */
    @GetMapping(value = {"/", "/index"})
    public ModelAndView index() {
        return new ModelAndView(PATH + "index");
    }

    /**
     * description：查询用户列表（分页）
     * user 朱正磊
     * time 2019-03-26 17:32
     * @param searchText 查询条件
     * @return 返回响应结果
     */
    @PostMapping("/list")
    @ResponseBody
    public Page<User> list(@RequestParam(value = "searchText", required = false) String searchText) {
        return userService.findAllByLike(searchText, getPageRequest());
    }

    /**
     * description：请求访问用户新增表单页
     * user 朱正磊
     * time 2019-03-26 17:37
     * @return 返回模型视图
     */
    @GetMapping("/add")
    public ModelAndView add() {
        return new ModelAndView(PATH + "form");
    }

    /**
     * description：请求访问用户修改表单页
     * user 朱正磊
     * time 2019-03-26 17:43
     * @param id 用户ID
     * @param map 响应数据
     * @return 返回模型视图
     */
    @GetMapping("/edit/{id}")
    public ModelAndView edit(@PathVariable Integer id, Map<String, Object> map) {
        User user = userService.findById(id);
        map.put("user", user);
        return new ModelAndView(PATH + "form", map);
    }

    /**
     * description：增加或者修改用户
     * user 朱正磊
     * time 2019-03-26 17:49
     * @param user 用户对象
     * @return 返回响应结果
     */
    @PostMapping("/edit")
    @ResponseBody
    public JsonResult edit(User user) {
        try {
            userService.saveOrUpdate(user);
        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    /**
     * description：根据主键删除一条记录
     * user 朱正磊
     * time 2019-03-26 17:52
     * @param id 用户ID
     * @return 返回响应结果
     */
    @GetMapping("/delete/{id}")
    @ResponseBody
    public JsonResult delete(@PathVariable Integer id) {
        try {
            userService.delete(id);
        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    /**
     * description：访问给用户分配角色页面
     * user 朱正磊
     * time 2019-03-26 18:02
     * @param id 用户ID
     * @param map 响应数据
     * @return 返回模型视图
     */
    @GetMapping("/grant/{id}")
    public ModelAndView grant(@PathVariable Integer id, Map<String, Object> map) {
        //获取用户信息
        User user = userService.findById(id);
        map.put("user", user);

        //获取用户角色ID集合
        List<Integer> roleIds = user.getRoles().stream().map(Role::getId).collect(Collectors.toList());
        map.put("roleIds", roleIds);

        //获取所有角色
        List<Role> roles = roleService.findAll();
        map.put("roles", roles);

        return new ModelAndView(PATH + "grant");
    }

    /**
     * description：给用户分配角色
     * user 朱正磊
     * time 2019-03-26 18:02
     * @param id 主键
     * @param roleIds 角色ID数组
     * @return 返回响应结果
     */
    @PostMapping("/grant/{id}")
    @ResponseBody
    public JsonResult grant(@PathVariable Integer id, String[] roleIds) {
        try {
            userService.grant(id, roleIds);
        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    /**
     * description：访问修改用户密码页面
     * user 朱正磊
     * time 2019-03-26 18:02
     * @return 返回模型视图
     */
    @GetMapping("/updatePwd")
    public ModelAndView updatePwd() {
        return new ModelAndView(PATH + "updatePwd");
    }

    /**
     * description：修改用户密码
     * user 朱正磊
     * time 2019-03-26 18:02
     * @param oldPassword 原始密码
     * @param password1 新密码
     * @param password2 确认密码
     * @return 返回响应结果
     */
    @PostMapping("/updatePwd")
    @ResponseBody
    public JsonResult updatePwd(String oldPassword, String password1, String password2) {
        try {
            Subject subject = SecurityUtils.getSubject();
            User user = (User) subject.getPrincipal();
            if (EmptyUtil.isEmpty(user)) {
                return JsonResult.failure("您尚未登录！");
            }
            userService.updatePwd(user, oldPassword, password1, password2);
        } catch (Exception e) {
            return JsonResult.failure(e.getMessage()); //错误消息为我们的自定义异常信息
        }
        return JsonResult.success();
    }

}
